// components/authorize/authorize.js
const wxaUserService = require('../../api/wxaUserService.js')
const systemService = require('../../api/systemService.js')
const storeService = require('../../api/storeService.js')
const wxaExperienceService = require('../../api/wxaExperienceService.js')
const auth = require('../../utils/auth.js')
const util = require('../../utils/utils.js')
var QQMapWX = require('../../libs/qqmap-wx-jssdk.min.js');
var qqmapsdk;

//获取应用实例
const app = getApp();

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    onClickLogin: {
      type: Boolean,
      value: true
    },
    showPhone: Boolean,
    onPopupPhone: {
      type: Boolean,
      value: true
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    show: {
      middle: false,
      login: false,
      phone: false,
      customer: false
    },
    overlayStyle: '',
    hasPhoneNumber: false,
    phoneNumber: '',
    canIUse: wx.canIUse('button.open-type.openSetting'),
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
  },
  // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
  attached: function () {}, // 此处attached的声明会被lifetimes字段中的声明覆盖
  ready: function () {
    console.log("components ready")
    if (!app.globalData.userInfo) {
      this.setData({
        [`show.login`]: true
        // 'show.login':true
      });
      this.handleTabBar(false)
    } else {
      if (this.data.show.login) {
        this.setData({
          [`show.login`]: false
        });
      } else {
        const that = this
        let user = app.globalData.userInfo
        if (app.globalData.scene !== 'isfromQR') {
          wxaExperienceService.checkHasExperiencer(user.wxaUser.openId).then(res => {
            console.log(res)
            if (res === false) {
              that.handleTabBar(false)
              that.setData({
                [`show.customer`]: true
              });
            } else {
              that.onSuccess()
            }
          }).catch(err => {
            wx.showToast({
              title: err.message,
              icon: 'none',
              duration: 2000
            })
          })
        }
      }
    }
    const self = this
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: 'AD5BZ-CHCKS-64OOD-6G6TX-BSOA6-IFF3V'
    });
    if (app.globalData.addressInfo) {
      let latitude = app.globalData.addressInfo.lat;
      let longitude = app.globalData.addressInfo.lng;
      self.getAllStoreInfo(latitude, longitude);
    } else {
      //1、获取当前位置坐标
      wx.getLocation({
        type: 'gcj02',
        success: function (res) {
          let latitude = res.latitude
          let longitude = res.longitude
          // 2.根据当前位置，获取最近的几个门店信息
          self.getAllStoreInfo(latitude, longitude);
        }
      })
    }
  },
  show: function () {
    console.log("components show")
  },

  pageLifetimes: {
    // 组件所在页面的生命周期函数
    show: function () {
      // 基础库2.23以上触发
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onSuccess() {
      this.triggerEvent('login-result');
      this.handleTabBar(true)
      if (this.data.onClickLogin) {
        this.triggerEvent('login');
      }
    },
    onPopupPhone() {
      this.triggerEvent('popup-phone');

      if (!this.data.onPopupPhone) {
        this.triggerEvent('phone');
      }
    },
    handleTabBar(val) {
      let that = this
      var myEventDetail = {
        showTabbar: val
      } // detail对象，提供给事件监听函数
      var myEventOption = {} // 触发事件的选项
      that.triggerEvent('tabBar', myEventDetail, myEventOption)
    },
    triggerBindMobile(val) {
      let that = this
      var eventDetail = {
        bindMobile: val
      } // detail对象，提供给事件监听函数
      var eventOption = {} // 触发事件的选项
      that.triggerEvent('phone', eventDetail, eventOption)
    },
    getUserInfo: function (e) {
      console.log(e)
      const that = this
      if (e) {
        wx.setStorage({
          key: "wj_userInfo",
          data: e.detail.userInfo
        })
      }
      wxaUserService.login().then(res => {
        console.log(res)
        auth.setUser(res)
        app.globalData.userInfo = res
        if (!res.member) {
          that.setData({
            user: res.wxaUser,
            hasUserInfo: true,
          })
          that.toggleMiddlePopup()
          // that.togglePhonePopup()
        } else {
          if (that.data.show.login) {
            that.toggleMiddlePopup()
          }
          that.triggerBindMobile(true)
          that.setData({
            hasUserInfo: true
          })
          wx.setStorage({
            key: "wj_member",
            data: res.member
          })
          wxaExperienceService.checkHasExperiencer(res.wxaUser.openId).then(res => {
            console.log(res)
            if (app.globalData.scene !== 'isfromQR') {
              if (res === false) {
                that.setData({
                  [`show.customer`]: true
                });
              } else {
                that.onSuccess()
              }
            } else {
              that.onSuccess()
            }
          }).catch(err => {
            wx.showToast({
              title: err.message,
              icon: 'none',
              duration: 2000
            })
          })
        }
      }).catch(err => {
        console.log(err)
        this.setData({
          hasUserInfo: false
        })
        if (err.message.indexOf("auth deny") >= 0) {
          wx.showToast({
            title: "您拒绝了授权~",
            icon: 'none',
            duration: 2000
          })
        } else {
          wx.showToast({
            title: err.message,
            icon: 'none',
            duration: 2000
          })
        }
      });
      // this.setData({
      //   userInfo: e.detail.userInfo,
      //   hasUserInfo: true
      // })
    },
    /**
     * 强制用户绑定流程
     *  登录框（强制）
     *  手机号授权
     *  同意    不同意（返回上一步）
     *  手机号确认
     *  确认绑定                                                   修改手机号
     *  绑定成功   绑定失败                                         成功              失败
     *  关闭弹框   提示失败跳转手动绑定                              返回（关闭弹窗）   返回不关闭弹窗
     *            成功（关闭弹框）  失败（手机号确认弹窗界面）
     */
    // 获取微信用户绑定的手机号
    getPhoneNumber: function (e) {
      console.log(e)
      if (e.detail.errMsg.indexOf("ok") >= 0) {
        wxaUserService.parseWxaMobile(e.detail.encryptedData, e.detail.iv).then(res => {
          console.log(res)
          this.setData({
            hasPhoneNumber: true,
            phoneNumber: res,
            encryptedData: e.detail.encryptedData,
            iv: e.detail.iv
          })
        }).catch(err => {
          wx.showToast({
            title: "未知错误，即将跳转到手动绑定手机号",
            icon: 'none',
            duration: 2000
          })
          setTimeout(function () {
            wx.navigateTo({
              url: 'pages/memberModule/bindMobile/bindMobile',
            })
          }, 2000)
        })
      } else {
        wx.showToast({
          title: "获取手机号失败，即将跳转到手动绑定手机号",
          icon: 'none',
          duration: 2000
        })
        setTimeout(function () {
          wx.navigateTo({
            url: 'pages/memberModule/bindMobile/bindMobile',
          })
        }, 2000)
      }
    },
    toBindMobile: function () {
      wx.navigateTo({
        url: 'pages/memberModule/bindMobile/bindMobile'
      })
    },
    // 绑定手机号
    handleBindMobile: function () {
      var self = this;
      let storeId = ''
      if (app.globalData.storeInfo) {
        console.log(app.globalData.storeInfo)
        if (app.globalData.systemConfigure.memberAscriptionStoreDistance && app.globalData.storeInfo.distance) {
          let distance = app.globalData.storeInfo.distance
          distance = parseFloat(distance * 1000)
          if (distance < app.globalData.systemConfigure.memberAscriptionStoreDistance) {
            console.log(distance, app.globalData.systemConfigure.memberAscriptionStoreDistance)
            storeId = app.globalData.storeInfo.id
          }
        }
      } else {

      }
      wxaUserService.bindMobileByEncrypt(this.data.encryptedData, this.data.iv, 'WXAPP', storeId).then(res => {
        console.log(res)
        self.triggerBindMobile(true)
      }).then(res => {
        self.getUserInfo()
      }).catch(err => {
        console.log(err)
        if (err.code === 23002) {
          self.triggerBindMobile(true)
          self.getUserInfo()
        } else {
          wx.showToast({
            title: err.message,
            icon: 'none',
            duration: 2000
          })
        }
      })
    },
    /**
     * 打开分享弹窗
     */
    toggleBottomPopup() {
      this.toggle('middle');
    },
    toggleMiddlePopup() {
      this.toggle('login');
    },
    togglePhonePopup() {
      this.toggle('phone');
      if (!this.data.show.phone) {
        this.triggerBindMobile(true)
      }
    },
    catchtouchmove: function () {

    },
    toggle(type) {
      this.setData({
        [`show.${type}`]: !this.data.show[type],
        [`overlayStyle`]: this.data.overlayStyle
      });
    },
    // 获取所有门店信息
    getAllStoreInfo: function (latitude, longitude) {
      const self = this
      try {
        var tempAllStores = wx.getStorageSync('wj_allStores'); // 获取缓存的所有门店
        if (tempAllStores) {
          // Do something with return value
          let tempIndex = self.getNearestStore(tempAllStores, latitude, longitude);
          app.globalData.storeInfo = tempAllStores[tempIndex];
          // 获取当前位置到最近门店的距离
          self.calcStoreDistance(tempAllStores[tempIndex], latitude, longitude)
        } else {
          // 查询所有门店
          storeService.queryList().then(res => {
            var allStores = [];
            res.forEach(item => {
              if (item.status === 'OPEN') {
                allStores.push(item)
              }
            });
            try {
              wx.setStorageSync('wj_allStores', allStores)
            } catch (e) {
              console.log(e)
            }
            let tempIndex = self.getNearestStore(allStores, latitude, longitude);
            return allStores[tempIndex]
          }).then(res => {
            app.globalData.storeInfo = res;
            self.calcStoreDistance(res, latitude, longitude)
          })
        }
      } catch (e) {
        // Do something when catch error
      }
    },
    // 获取最近的一家门店
    getNearestStore: function (allStores, latitude, longitude) {
      var distanceArr = [];
      allStores.forEach(item => {
        let dis = util.distance(latitude, longitude, item.latitude, item.longitude);
        distanceArr.push(dis);
      })
      // 计算最小值
      const minN = Math.min.apply(Math, distanceArr);
      let tempIndex = 0;
      for (var i = 0; i < distanceArr.length; i++) {
        if (minN === distanceArr[i]) {
          tempIndex = i;
          break;
        }
      }
      this.setData({
        store: allStores[tempIndex].name,
        storeId: allStores[tempIndex].id
      })
      return tempIndex;
    },
    // 获取用户到门店的距离
    calcStoreDistance: function (stores, latitude, longitude) {
      let dis = util.distance(latitude, longitude, stores.latitude, stores.longitude);
      let store = {
        ...stores,
        distance: dis
      }
      app.globalData.storeInfo = store
      this.setData({
        storeInfo: store
      })
    },
    saveCustomerInfo: function (val) {
      const that = this
      console.log(val.detail.value)
      const company = val.detail.value.company
      const name = val.detail.value.name
      const phone = val.detail.value.phone
      const openId = app.globalData.userInfo.wxaUser.openId
      if (company !== '' && name !== '' && this.checkMobile(phone)) {
        wxaExperienceService.create(company, phone, name, openId).then(res => {
          console.log(res)
          wx.showToast({
            title: '信息提交成功~',
            icon: 'none',
            duration: 1000
          })
          setTimeout(() => {
            that.toggle('customer');
            that.onSuccess()
          }, 1000);
        }).catch(err => {
          wx.showToast({
            title: err.message,
            icon: 'none',
            duration: 2000
          })
        })
      } else {
        if (name == '') {
          wx.showToast({
            title: '请输入姓名~',
            icon: 'none',
            duration: 2000
          })
        } else if (company == '') {
          wx.showToast({
            title: '请输入公司名称~',
            icon: 'none',
            duration: 2000
          })
        } else if (phone == '') {
          wx.showToast({
            title: '请输入联系方式~',
            icon: 'none',
            duration: 2000
          })
        } else {

        }
      }
    },
    // 检查手机号
    checkMobile: function (mobile) {
      let reg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/
      if (!mobile) {
        wx.showToast({
          title: "请填写手机号",
          icon: 'none',
          duration: 2000
        })
        return false;
      } else if (!reg.test(mobile)) {
        wx.showToast({
          title: "请填写正确的手机号",
          icon: 'none',
          duration: 2000
        })
        return false;
      } else {
        return true;
      }
    },
    // 处理姓名输入
    handleName: function (e) {
      if (e.detail.cursor < 5) {

      } else if (e.detail.cursor === 5) {
        wx.showToast({
          title: '联系人昵称最大不能超10个字符哦~',
          icon: 'none',
          duration: 2000
        })
      } else {

      }
    },
    // 处理公司名称输入
    handleCompany: function (e) {
      if (e.detail.cursor < 20) {

      } else if (e.detail.cursor === 20) {
        wx.showToast({
          title: '公司名称最大不能超20个字符哦~',
          icon: 'none',
          duration: 2000
        })
      } else {

      }
    },
  }
})